/*
 * Copyright (C) 2010 Tetsuya Yasuda <tetsuyayasuda@gmail.com>
 */
package jp.tyas.libs.terminal;

import java.util.Vector;

public class TerminalBuffer {

	int max;
	Vector fixed = new Vector();
	StringBuffer inb = new StringBuffer();
	StringBuffer outb = new StringBuffer();
	TextUpdatedListener l = null;

    public interface TextUpdatedListener {
    	public void textUpdated();
    }
	
    public void setTextUpdatedListener(TextUpdatedListener l) {
    	this.l = l;
    }
    
	public TerminalBuffer(int max) {
		this.max = max;
	}
	
	public synchronized String putCharIn(char c) {
		String ret = null;
		switch (c) {
		case '\n':
			ret = inb.toString();
			fixed.add(outb.toString() + ret);
			inb = new StringBuffer();
			outb = new StringBuffer();
			break;
		case '\b':
			if (inb.length() > 1)
				inb.deleteCharAt(inb.length()-1);
			break;
		default:
			inb.append(c);
			break;
		}
		if (l != null) l.textUpdated();
		return ret;
	}
	
	public synchronized void putCharOut(char c) {
		switch (c) {
		case '\n':
			fixed.add(outb.toString());
			outb = new StringBuffer();
                        if (l != null) l.textUpdated();
			break;
		default:
			outb.append(c);
			break;
		}
                //if (l != null) l.textUpdated();
	}
	
	public int size() {
		return fixed.size() + 1;
	}
	
	public String getLine(int i) {
		if (i == fixed.size())
			return outb.toString() + inb.toString();
		return (String) fixed.get(i);
	}
}
